package com.huishi.handler.ws;

import com.huishi.config.ServiceConfig;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;

@Component
@Slf4j
public class MyWebSocketClient {
    @Autowired
    private ServiceConfig serviceConfig;

    @Bean
    public WebSocketClient webSocketClient() throws URISyntaxException, UnknownHostException {
        // 建立ws连接对象
        WebSocketClient webSocketClient = getClient();

        webSocketClient.connect();
        return webSocketClient;
    }

    public WebSocketClient getClient() throws UnknownHostException, URISyntaxException {
        String IP = InetAddress.getLocalHost().getHostAddress();
        // 建立ws连接对象
        WebSocketClient webSocketClient =
                new WebSocketClient(
                        new URI("ws://" + serviceConfig.getHost() + ":" + serviceConfig.getPort() + "/webSocket/" + IP),
                        new Draft_6455()) {

                    @Override
                    public void onOpen(ServerHandshake handshakedata) {
                        log.info("[websocket] 连接成功");
                    }

                    @Override
                    public void onMessage(String message) {
                        log.info("[websocket] 收到消息={}", message);

                    }

                    @Override
                    public void onClose(int code, String reason, boolean remote) {
                        log.info("[websocket] 退出连接");
                    }

                    @Override
                    public void onError(Exception ex) {
                        log.info("[websocket] 连接错误={}", ex.getMessage());
                    }
                };

        return webSocketClient;
    }
}
